// pages/member/cart/index.js
var app = getApp();
var diyad = app.requirejs('biz/ad');
var diypage = app.requirejs('biz/diypage');
var core = app.requirejs('core');
var $ = app.requirejs('jquery');
var mainui = app.requirejs('mainui');
const api = require("../../../utils/api.js")
const authScope = require("../../../utils/auth.js")
Page(app.sr.page({

  /**
   * 页面的初始数据
   */
  data: {
    isEmpty: 2,
    isLogin: false,
    isCheckAll: 1, //全选
    totalprice: 0,
    optionId: '',
    list: [],
    flang: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options) {
      this.setData({
        optionId: 204
      })
    }
    let isLogin = app.checkAuth();
    this.setData({
      isLogin
    })
    wx.hideTabBar({
      // animation: true,
    })
    // 自定义页
    diypage.get(this, "diy", {
      id: '2'
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let _this = this
    app.miniprogram(function (res) {
      _this.setData({
        bindingNodes: res.bindingNodes
      })
    })
    _this.initFunction();
  },
  //去逛逛去首页
  goIndex: function () {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  //登录授权
  bindGetUserInfo() {
    var that = this;
    authScope.scopeLogin().then((res) => {
      if (res) {
        this.setData({
          isLogin: true
        })
        that.onShow();
      }
    })
  },

  initFunction: function () {
    this.get_cart();
    var $this = this;
    /**启动广告 */
    diyad.get(this, function (res) {

    })
  },
  //购物车列表
  get_cart: function () {
    let $this = this,
      setData;
    let apicontent = api.orders.getCart()
    let data = {}
    core.get(apicontent, {
      ...data
    }, function (res) {
      // 埋点用
      // let totaltitle = [];
      // res.data.forEach(e => {
      //   if (e.selected == 1) {
      //     totaltitle.push(e.title)
      //   }
      // })
      // totaltitle = totaltitle.join("|")
      setData = {
        show: true,
        totalprice: res.data.totalprice,
        empty: res.data.empty || false,
      };
      setData.list = res.data.cartList || [];
      setData.isCheckAll = res.data.isCheckAll
      setData.isEmpty = res.data.isEmpty
      //所有的cartid 全选传的ids
      let allcartid = []
      let allgood = []
      //所有被选中的ids 用于预览订单
      let checkcartid = []
      setData.totalprice = 0
      res.data.cartList.forEach(e => {
        allcartid.push(e.esShopCart.id)
        if (e.esShopCart.isSelected == 1) {
          checkcartid.push(e.esShopCart.id)
          setData.totalprice += e.esShopCart.total * e.esShopCart.price
          allgood.push(e.esShopCart.goodsId)
        }
      })
      setData.totalprice = setData.totalprice.toFixed(2)
      setData.AllCartId = allcartid.join(",")
      setData.CheckCartId = checkcartid.join(",")
      setData.AllGoods = allgood.join(",")
      $this.setData(setData)
      //查找礼品商品
      if ($this.data.optionId && $this.data.flang) {
        let add1 = $this.findgoods('201').join()
        let add2 = $this.findgoods('202').join()
        let add3 = $this.findgoods('203').join()
        let add4 = $this.findgoods('204').join()
        let apicontent = api.orders.getQuantity()
        core.post(apicontent, {
          id: add1,
          total: 1,
        })
        core.post(apicontent, {
          id: add2,
          total: 1,
        })
        core.post(apicontent, {
          id: add3,
          total: 1,
        })
        core.post(apicontent, {
          id: add4,
          total: 1,
        }, function () {

          $this.setData({
            flang: false
          })
          $this.get_cart();
        })
      }
    });
  },
  //编辑商品信息  删除 去结算
  edit: function (e) {
    let goods = e.currentTarget.dataset.esshopcart

    let index = e.currentTarget.dataset.index;
    var dataset = core.data(e),
      $this = this,
      ids = $this.data.CheckCartId;
    switch (dataset.action) {
      case 'delete':
        ids = $.trim(e.target.dataset.id);
        let apicontent = api.orders.getDelete()
        // if (!$.isEmptyObject(ids)) {

        core.confirm('是否确认删除该商品?', function () {
          console.log(goods)
          app.sr.track('add_to_cart', {
            action_type: 'remove_from_cart',
            sku_num: 0,
            "sku": {
              "sku_id": String(goods.optionId),
              "sku_name": goods.optionName
            },
            "spu": {
              "spu_id": String(goods.goodsId),
              "spu_name": goods.goodsName
            },
          })
          core.post(apicontent, {
            ids: ids
          }, function (data) {
            $this.get_cart();
          });
        })
        // }
        break;
      case 'pay':
        // 绑定节点为立即购买节点
        let mobile = app.getCache('mobile');
        if ($this.data.bindingNodes == 2 && mobile.length < 1) {
          core.alert("请绑定手机", function () {

            wx.navigateTo({
              url: '/pages/member/bind/index',
            })
          })
          return
        }
        if (this.data.totalprice > 0) {
          wx.navigateTo({
            url: '/pages/order/create/index?ids=' + ids + "&type=2"
          });
        } else {
          core.toast("请选择商品", "none")
        }
        break;
    }
  },
  // 修改数量 需重新获取购物车
  number: function (e) {
    console.log(e)
    let goods = e.currentTarget.dataset.esshopcart
    let index = e.currentTarget.dataset.index,
      id = e.currentTarget.dataset.id,
      total = e.currentTarget.dataset.total,
      apicontent = api.orders.getQuantity(),
      $this = this,
      dataset = core.pdata(e),
      val = mainui.number(this, e);
    if ((val == 1 && dataset.value == 1 && e.target.dataset.action == 'minus') || (dataset.value == dataset.max && e.target.dataset.action == 'plus')) {
      return;
    } else if (e.target.dataset.action == 'minus') {
      app.sr.track('add_to_cart', {
        action_type: 'remove_from_cart',
        sku_num: 1,
        "sku": {
          "sku_id": String(goods.optionId),
          "sku_name": goods.optionName
        },
        "spu": {
          "spu_id": String(goods.goodsId),
          "spu_name": goods.goodsName
        },
      })
      total -= 1;
      core.post(apicontent, {
        id,
        total,
      }, function (data) {
        $this.get_cart();
      });
    } else if (e.target.dataset.action == 'plus') {
      app.sr.track('add_to_cart', {
        action_type: 'append_to_cart_in_cart',
        sku_num: 1,
        "sku": {
          "sku_id": String(goods.optionId),
          "sku_name": goods.optionName
        },
        "spu": {
          "spu_id": String(goods.goodsId),
          "spu_name": goods.goodsName
        },
      })
      total += 1;
      core.post(apicontent, {
        id,
        total,
      }, function (data) {
        $this.get_cart();
      });
    }
  },
  //选择商品
  selected: function (e) {
    core.loading();
    //console.log(e.target);
    var $this = this,
      dataset = core.pdata(e),
      id = dataset.id,
      select = dataset.select == 1 ? 2 : 1,
      apicontent = api.orders.getisCheckCart()

    //console.log(select)
    let gxtitle = select == 1 ? "勾选" : "取消勾选"
    core.post(apicontent, {
      ids: id,
      isSelected: select
    }, function (data) {
      $this.get_cart();
      core.hideLoading();
    })
    if (select == 0) { }
  },
  //全选
  checkall: function (e) {
    core.loading();
    var $this = this,
      apicontent = api.orders.getisCheckCart(),
      //1,//  全选 2 没有全选，没有数据 也是全选，需要做处理
      select = this.data.isCheckAll == 1 ? 2 : 1;
    core.post(apicontent, {
      ids: $this.data.AllCartId,
      isSelected: select
    }, function (data) {
      console
      $this.get_cart();
      core.hideLoading();
    });
  },

  //获取图片高度
  imagesHeight: function (e) {
    var width = e.detail.width,
      height = e.detail.height,
      type = e.target.dataset.type,
      $this = this;

    var isdot = e.currentTarget.dataset.isdot
    wx.getSystemInfo({
      success: function (res) {
        if (isdot == "dot_inside") {
          $this.data.result[type] = Number(res.windowWidth / width * height);
        } else {
          $this.data.result[type] = Number(res.windowWidth / width * height) + 30;

        }
        if (!$this.data[type] || ($this.data[type] && result[type] < $this.data[type])) {
          $this.setData({
            result: $this.data.result
          });
        }
      }
    });
  },
  //商品跳转
  toShopDetail(e) {
    let shopId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/goods/detail/index?id=' + shopId,
    })
  },
  //查找商品id
  findgoods(add) {
    var id = []
    this.data.list.map(asd => {
      if (asd.esShopCart.optionId == add) {
        id.push(asd.esShopCart.id)
      }
    })
    return id
  }
}))